package hd

import (
	"fmt"
	"sync"
	"time"
)

/*
Error Error
*/
type Error int

var errMap map[int]string
var errLastLoad time.Time
var errLock sync.RWMutex
var errLoad func(f string) map[int]string
var errFirstedLoaded = false

func (e Error) Error() string {
	errLock.RLock()
	er, ok := errMap[int(e)]
	lastl := errLastLoad
	errLock.RUnlock()
	if ok {
		return er
	} else if time.Now().Unix()-lastl.Unix() > 10*60 {
		_errmap := errLoad("data/errorcode.ini")
		if _errmap != nil && len(_errmap) > 0 {
			errLock.Lock()
			errMap = _errmap
			errLastLoad = time.Now()
			er, ok := errMap[int(e)]
			errLock.Unlock()
			if ok {
				return er
			}
		}
	}

	return fmt.Sprint("ERROR ", int(e))
}

/*
ErrCode 构造错误码
*/
func ErrCode(code int) error {
	return Error(code)
}

/*
ErrSetLoad 设置错误码文字加载函数
*/
func ErrSetLoad(f func(f string) map[int]string) {
	errLoad = f
	_errmap := errLoad("res/ini/platform/errorcode.ini")
	if _errmap != nil && len(_errmap) > 0 {
		errLock.Lock()
		errMap = _errmap
		errLastLoad = time.Now()
		errLock.Unlock()
	}
}
